package com.youmingxing.fragment;


import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.youmingxing.R;
import com.youmingxing.data.GlobalDataManager;
import com.youmingxing.network.AllStarApi;
import com.youmingxing.network.BaseJsonHandler;
import com.youmingxing.view.DialogManager;
import com.youmingxing.view.LineTabIndicator;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 海选页面
 * 活动Tab  页面
 *
 * @author evilyin(ChenZhixi)
 * @since 15/9/1
 */

public class AuditionFragment extends Fragment {

    private View view;
    private List<Fragment> fragments;
    private List<String> titles;
    private MyPagerAdapter adapter;
    private ViewPager pager;
    private LineTabIndicator indicator;
    private LinearLayout mainLayout;
    private RelativeLayout errorLayout;
    private boolean isFirstLoad = true;

    public AuditionFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        fragments = new ArrayList<>();
        titles = new ArrayList<>();

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (view == null) {

            view = inflater.inflate(R.layout.fragment_audition, container, false);
            pager = (ViewPager) view.findViewById(R.id.pager);
            indicator = (LineTabIndicator) view.findViewById(R.id.line_tab_indicator);
            mainLayout = (LinearLayout) view.findViewById(R.id.main_layout);
            errorLayout = (RelativeLayout) view.findViewById(R.id.error);
            errorLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    DialogManager.showDialog(getActivity(), "正在拼命加载");
                    loadData();
                }
            });
            loadData();
        }
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!isFirstLoad) { //如果是第一次加载,不在onResume里setTab
            setTab();
        }
        isFirstLoad = false;
    }

    private void loadData() {
        AllStarApi.getMovieList(new BaseJsonHandler(getActivity()) {
            @Override
            public void onSuccessWithData(JSONObject response) {
                mainLayout.setVisibility(View.VISIBLE);
                errorLayout.setVisibility(View.GONE);
                JSONArray data = response.optJSONArray("data");
                int titleLen =0;
                for (int i = 0; i < data.length(); i++) {
                    JSONObject thisMovie = data.optJSONObject(i);
                    titles.add(thisMovie.optString("name"));
                    titleLen = titleLen + thisMovie.optString("name").length();
                    MovieFragment movieFragment = new MovieFragment();
                    Bundle bundle = new Bundle();
                    bundle.putInt("id", thisMovie.optInt("id"));
                    movieFragment.setArguments(bundle);
                    fragments.add(movieFragment);
                }
                adapter = new MyPagerAdapter(getChildFragmentManager(), fragments, titles);
                pager.setAdapter(adapter);
                if (titles.size() > 5) {
                    indicator.setEnableExpand(false);
                }
                indicator.setViewPager(pager);
                setTab();
            }

            @Override
            public void onFail(int statusCode, String statusText) {
                mainLayout.setVisibility(View.GONE);
                errorLayout.setVisibility(View.VISIBLE);
            }
        });

    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (view != null) {
            ((ViewGroup) view.getParent()).removeView(view);
        }
    }

    public void setTab() {
        if (GlobalDataManager.needSetTab && GlobalDataManager.tab < titles.size()) {
            pager.setCurrentItem(GlobalDataManager.tab);
            GlobalDataManager.tab = 0;
            GlobalDataManager.needSetTab = false;
            GlobalDataManager.save();
        }
    }


    class MyPagerAdapter extends FragmentPagerAdapter {

        private List<Fragment> fragmentList;
        private List<String> titleList;

        public MyPagerAdapter(FragmentManager fm, List<Fragment> fragmentList, List<String> titleList) {
            super(fm);
            this.fragmentList = fragmentList;
            this.titleList = titleList;
        }

        /**
         * 得到每个页面
         */
        @Override
        public Fragment getItem(int arg0) {
            return (fragmentList == null || fragmentList.size() == 0) ? null : fragmentList.get(arg0);
        }

        /**
         * 每个页面的title
         */
        @Override
        public CharSequence getPageTitle(int position) {
            return (titleList.size() > position) ? titleList.get(position) : "";
        }

        /**
         * 页面的总个数
         */
        @Override
        public int getCount() {
            return fragmentList == null ? 0 : fragmentList.size();
        }
    }
}
